import {
  addCodeTableUsingPost,
  updateCodeTableUsingPut,
} from '@/services/data-factory/mabiaoguanli';
import {
  ModalForm,
  ProForm,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, Form, Input, message, Space } from 'antd';
import { useEffect, useState } from 'react';

interface CodeFormProps {
  open: boolean;
  onSuccess: () => void;
  onCancel: () => void;
  editData?: {
    codeId: number;
    codeName: string;
    codeExplain: string;
    codeValueList: CodeValueItem[]; // 修改为对象数组类型
    codeTableId: number;
    status: string;
  };
}

interface CodeValueItem {
  codeTableId: number;
  codeValue: number;
  codeValueName: string;
  codeValueMean: string;
}

const CodeForm: React.FC<CodeFormProps> = ({
  open,
  onCancel,
  onSuccess,
  editData,
}) => {
  const [form] = Form.useForm();
  const [codeValues, setCodeValues] = useState<CodeValueItem[]>([]);

  useEffect(() => {
    if (editData) {
      form.setFieldsValue({
        codeName: editData.codeName,
        codeExplain: editData.codeExplain,
      });

      // 直接设置码值列表
      setCodeValues(editData.codeValueList || []);
    }
  }, [editData, form]);

  const handleReset = () => {
    form.resetFields();
    setCodeValues([]);
  };

  const handleAdd = () => {
    setCodeValues([
      ...codeValues,
      {
        codeValue: 0,
        codeTableId: editData?.codeTableId || 0,
        codeValueName: '',
        codeValueMean: '',
      },
    ]);
  };

  const handleDelete = (index: number) => {
    const newValues = [...codeValues];
    newValues.splice(index, 1);
    setCodeValues(newValues);
  };

  // 添加中文和英文字符的验证规则
  const validateChineseAndEnglish = (rule: any, value: string) => {
    const pattern = /^[\u4e00-\u9fa5a-zA-Z]+$/;
    if (!pattern.test(value)) {
      return Promise.reject('只能输入中文和英文字母');
    }
    return Promise.resolve();
  };

  // 检查码值是否重复
  const checkDuplicateValues = (values: CodeValueItem[]) => {
    const codeValues = values.map((item) => item.codeValue);
    const codeNames = values.map((item) => item.codeValueName);

    // 检查码值重复
    const duplicateValues = codeValues.filter(
      (value, index) => codeValues.indexOf(value) !== index,
    );
    if (duplicateValues.length > 0) {
      message.error('编码取值不能重复');
      return true;
    }

    // 检查码值名称重复
    const duplicateNames = codeNames.filter(
      (name, index) => codeNames.indexOf(name) !== index,
    );
    if (duplicateNames.length > 0) {
      message.error('编码中文名称不能重复');
      return true;
    }

    return false;
  };

  return (
    <ModalForm
      form={form}
      title={editData?.codeId ? '编辑码表' : '新增码表'}
      open={open}
      onOpenChange={(visible) => {
        if (!visible) {
          handleReset();
          onCancel();
        }
      }}
      width={800}
      modalProps={{
        destroyOnClose: true,
      }}
      onFinish={async (values) => {
        try {
          // 验证码值不能为空或空格
          for (const item of codeValues) {
            if (!item.codeValue || !item.codeValueName.trim()) {
              message.error('编码取值和编码中文名称不能为空或空格');
              return false;
            }
          }

          // 检查重复值
          if (checkDuplicateValues(codeValues)) {
            return false;
          }

          const submitData = {
            codeName: values.codeName,
            codeExplain: values.codeExplain,
            codeValue: codeValues.map((item) => item.codeValue),
            codeValueName: codeValues.map((item) => item.codeValueName),
            codeValueMean: codeValues.map((item) => item.codeValueMean || ''),
            codeTableId: codeValues.map((item) => item.codeTableId),
            status: editData?.status || '未发布',
          };

          let res;
          if (editData) {
            res = await updateCodeTableUsingPut({
              codeId: editData.codeId,
              ...submitData,
            });
          } else {
            res = await addCodeTableUsingPost(submitData);
          }

          if (res.code === 100200) {
            message.success(editData ? '编辑成功' : '新增成功');
            handleReset();
            onSuccess();
            return true;
          } else {
            // 处理码表名称重复的错误
            if (res.code === 100500 && res.msg?.includes('已存在')) {
              message.error('码表名称已存在');
            } else {
              message.error(res.msg || (editData ? '编辑失败' : '新增失败'));
            }
            return false;
          }
        } catch (error) {
          message.error(editData ? '编辑失败' : '新增失败');
          return false;
        }
      }}
    >
      <ProFormText
        name="codeName"
        label="码表名称"
        placeholder="请输入标准中文名称"
        rules={[
          { required: true, message: '请输入码表名称' },
          { validator: validateChineseAndEnglish },
        ]}
      />
      <ProFormTextArea
        name="codeExplain"
        label="码表说明"
        placeholder="请输入标准说明"
      />
      <ProForm.Item label="编码配置" required>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" onClick={handleAdd}>
            添加
          </Button>
        </div>
        {codeValues.map((item, index) => (
          <Space
            key={index}
            style={{ display: 'flex', marginBottom: 8 }}
            align="baseline"
          >
            {[
              {
                label: '码值取值',
                key: 'codeValue',
                required: true,
                type: 'number',
                rules: [{ required: true, message: '请输入码值' }],
              },
              {
                label: '码值名称',
                key: 'codeValueName',
                required: true,
                rules: [
                  { required: true, message: '请输入码值名称' },
                  { validator: validateChineseAndEnglish },
                ],
              },
              { label: '码值含义', key: 'codeValueMean' },
            ].map((field) => (
              <Form.Item
                key={field.key}
                label={field.label}
                required={field.required}
                style={{ marginBottom: 0 }}
                rules={field.rules}
              >
                <Input
                  type={field.type}
                  value={item[field.key as keyof CodeValueItem]}
                  onChange={(e) => {
                    const newValues = [...codeValues];
                    const value =
                      field.type === 'number'
                        ? Number(e.target.value)
                        : e.target.value;
                    (newValues[index] as any)[field.key] = value;
                    setCodeValues(newValues);
                  }}
                />
              </Form.Item>
            ))}
            <Button type="link" onClick={() => handleDelete(index)}>
              删除
            </Button>
          </Space>
        ))}
      </ProForm.Item>
    </ModalForm>
  );
};

export default CodeForm;
